package service

import (
	"fmt"
	"go-0650-blog-grom/dao/mysql"
	"go-0650-blog-grom/models"
	"go-0650-blog-grom/myUtil/snowflake"
	"go.uber.org/zap"
)

type PostService struct {
}

/**
 * @Author huchao
 * @Description //TODO 创建帖子
 * @Date 19:53 2022/2/12
 **/
func (con PostService) CreatePost(post *models.Post) (err error) {
	// 1、 生成post_id(生成帖子ID)
	postID, err := snowflake.GetID()
	if err != nil {
		zap.L().Error("snowflake.GetID() failed", zap.Error(err))
		return
	}
	post.PostID = postID

	// 2、创建帖子 保存到数据库
	if err := mysql.CreatePost(post); err != nil {
		zap.L().Error("mysql.CreatePost(&post) failed", zap.Error(err))
		return err
	}
	// post.CommunityID == (*post).CommunityID
	_, err = mysql.CommunityMapper{}.GetCommunityNameByID(fmt.Sprint(post.CommunityID))
	if err != nil {
		zap.L().Error("mysql.GetCommunityNameByID failed", zap.Error(err))
		return err
	}

	// 暂时略: redis存储帖子信息

	return

}

/**
 * @Author SSWANG
 * @Description //TODO 获取帖子列表
 * @Date 19:46 2022/10/28
 **/
func (con PostService) GetPostList(page, size int64) (data []*models.ApiPostDetail, err error) {
	postList, err := mysql.GetPostList(page, size)
	if err != nil {
		fmt.Println(err)
		return
	}
	data = make([]*models.ApiPostDetail, 0, len(postList)) // data 初始化
	for _, post := range postList {
		// 根据作者id查询作者信息
		user, err := mysql.GetUserByID(post.AuthorId)
		if err != nil {
			zap.L().Error("mysql.GetUserByID() failed",
				zap.Uint64("postID", post.AuthorId),
				zap.Error(err))
			continue
		}
		// 根据社区id查询社区详细信息
		community, err := mysql.CommunityMapper{}.GetCommunityByID(post.CommunityID)
		if err != nil {
			zap.L().Error("mysql.GetCommunityByID() failed",
				zap.Uint64("community_id", post.CommunityID),
				zap.Error(err))
			continue
		}
		// 接口数据拼接
		postdetail := &models.ApiPostDetail{
			Post:            post,
			CommunityDetail: community,
			AuthorName:      user.UserName,
		}
		data = append(data, postdetail)
	}
	return
}
